package org.atovio.coolexam.service.impl;

import org.atovio.coolexam.entity.ExamPaperAnswer;
import org.atovio.coolexam.exception.ServiceException;
import org.atovio.coolexam.mapper.ExamPaperAnswerMapper;
import org.atovio.coolexam.service.ExamPaperAnswerService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.Map;

@Service
@Transactional
public class ExamPaperAnswerServiceImpl implements ExamPaperAnswerService {

    private final ExamPaperAnswerMapper examPaperAnswerMapper;

    @Autowired
    public ExamPaperAnswerServiceImpl(ExamPaperAnswerMapper examPaperAnswerMapper) {
        this.examPaperAnswerMapper = examPaperAnswerMapper;
    }

    @Override
    public int getCount(Map<String, Object> criteria) {
        return examPaperAnswerMapper.selectCountSelective(criteria);
    }

    @Override
    public List<ExamPaperAnswer> getByStatus(Integer status) {
        return examPaperAnswerMapper.selectByStatus(status);
    }

    @Override
    public List<ExamPaperAnswer> getBySelective(Map<String, Object> criteria) {
        return examPaperAnswerMapper.selectSelective(criteria);
    }

    @Override
    public ExamPaperAnswer modifyStatusById(Integer id, Integer status) {
        int i = examPaperAnswerMapper.updateStatusById(id, status);
        if (i != 1) {
            throw new ServiceException("数据库错误");
        }
        return examPaperAnswerMapper.selectById(id);
    }

    @Override
    public ExamPaperAnswer modifyUserScoreById(Integer id, Integer userScore) {
        int i = examPaperAnswerMapper.updateUserScoreById(id, userScore);
        if (i != 1) {
            throw new ServiceException("数据库错误");
        }
        return examPaperAnswerMapper.selectById(id);
    }

    @Override
    public ExamPaperAnswer getById(Integer id) {
        return examPaperAnswerMapper.selectById(id);
    }

    @Override
    public ExamPaperAnswer add(ExamPaperAnswer examPaperAnswer) {
        int count = examPaperAnswerMapper.insert(examPaperAnswer);
        if (count != 1) {
            throw new ServiceException("数据库错误");
        }
        List<ExamPaperAnswer> answerPapers = examPaperAnswerMapper.selectSelective(
                Map.of("createUserId", examPaperAnswer.getCreateUserId(), "examPaperId", examPaperAnswer.getExamPaperId())
        );
        return answerPapers.get(0);
    }
}
